// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';
import LegalInfo from '../views/LegalInfo.vue';
import Consultation from '../views/Consultation.vue';
import CaseAssistance from '../views/CaseAssistance.vue';
import NotFound from '../views/NotFound.vue';
import holyGrailLayout from '../views/holyGrailLayout.vue';
import Login from '../views/Login.vue';
import Admin from '../views/Admin.vue';
import { useAuthStore } from '../stores/authStore';
import { generateDynamicRoutes } from './dynamicRoutes';
import UserManagement from '../views/UserManagement.vue';

const routes = [
    {
        path: '/',
        component: holyGrailLayout,
        redirect: '/home',
        meta: { requiresAuth: true },
        children: [
            {
                path: '/home',
                component: Home
            },
            { path: '/home/legal-info', component: LegalInfo },
            { path: '/home/consultation', component: Consultation },
            { path: '/home/case-assistance', component: CaseAssistance },
            { path: '/home/about', component: About },
            { path: '/admin', component: Admin },
            { path: '/user-management', component: UserManagement } // 添加用户管理路由
        ]
    },
    {
        path: '/login',
        component: Login
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: NotFound
    }
];

const router = createRouter({
    history: createWebHistory(),
    routes
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
    const authStore = useAuthStore();
    const isAuthenticated = authStore.isLoggedIn;
    const requiresAuth = to.matched.some(record => record.meta?.requiresAuth);

    if (authStore.isLoggedIn && !authStore.hasLoadedDynamicRoutes) {
        addRoutes(authStore.menuList);
        authStore.hasLoadedDynamicRoutes = true;
        return next({ path: to.fullPath, replace: true });
    }

    if (requiresAuth && !isAuthenticated) {
        next('/login');
    } else if (to.path === '/login' && isAuthenticated) {
        // 已登录用户访问 /login 自动跳转首页
        next('/home');
    } else {
        next();
    }
});

// 全局错误处理
router.onError((error) => {
    console.error('路由错误:', error);
});

export function addRoutes(menuList) {
    const newRoutes = generateDynamicRoutes(menuList);
    newRoutes.forEach(route => {
        router.addRoute(route);
    });

    router.addRoute({
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: NotFound
    });
}

// 导出 router 实例
export { router };
export default router;